/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.ohos.timber;

import java.io.Closeable;

import io.sentry.IHub;
import io.sentry.ILogger;
import io.sentry.Integration;
import io.sentry.SentryLevel;
import io.sentry.SentryOptions;
import io.sentry.protocol.SdkVersion;
import timber.log.Timber;

import static io.sentry.ohos.timber.BuildConfig.SENTRY_TIMBER_SDK_NAME;
import static io.sentry.ohos.timber.BuildConfig.VERSION_NAME;

/**
 * SentryTimberIntegration
 *
 * @since 2021-05-26
 */
public class SentryTimberIntegration implements Integration, Closeable {
    /**
     * MIN_EVENT_LEVEL
     */
    public static final SentryLevel MIN_EVENT_LEVEL = SentryLevel.ERROR;
    /**
     * MIN_BREADCRUMB_LEVEL
     */
    public static final SentryLevel MIN_BREADCRUMB_LEVEL = SentryLevel.INFO;

    private SentryTimberTree tree;
    private ILogger logger;

    /**
     * register
     *
     * @param hub the Hub
     * @param options the options
     */
    @Override
    public void register(IHub hub, SentryOptions options) {
        createSdkVersion(options);
        logger = options.getLogger();

        tree = new SentryTimberTree(hub, MIN_EVENT_LEVEL, MIN_BREADCRUMB_LEVEL);
        Timber.plant(tree);

        logger.log(SentryLevel.DEBUG, "SentryTimberIntegration installed.");
    }

    /**
     * close
     */
    @Override
    public void close() {
        Timber.uproot(tree);
        logger.log(SentryLevel.DEBUG, "SentryTimberIntegration removed.");
    }

    private SdkVersion createSdkVersion(SentryOptions options) {
        SdkVersion sdkVersion = options.getSdkVersion();

        String name = SENTRY_TIMBER_SDK_NAME;
        String version = VERSION_NAME;
        sdkVersion = SdkVersion.updateSdkVersion(sdkVersion, name, version);

        sdkVersion.addPackage("maven:io.sentry:sentry-ohos-timber", VERSION_NAME);

        return sdkVersion;
    }
}
